package org.jeecg.modules.sys_captcha.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.sys_captcha.service.ISysCaptchaService;
import org.jeecg.modules.wechat.service.WechatPaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Api(tags="验证码")
@RestController
@RequestMapping("/sys_captcha/sysCaptcha")
public class SysCaptchaController {

    @Autowired
    private ISysCaptchaService captchaService;
    @Autowired
    private WechatPaymentService wechatPaymentService;

    @ApiOperation(value="获取验证码", notes="获取验证码")
    @GetMapping(value = "/image")
    public void getCaptcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成唯一标识
        String uuid = UUID.randomUUID().toString();

        // 生成验证码图片
        BufferedImage image = captchaService.generateCaptcha(uuid);

        // 将UUID存入响应头
        response.setHeader("Captcha-UUID", uuid);

        // 输出图片流
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);

        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    @ApiOperation(value="验证验证码", notes="验证验证码")
    @GetMapping(value = "/validate")
    public Result<?> validate(@RequestParam("uuid") String uuid,
                              @RequestParam("code") String code,
                              @RequestParam(name = "phoneNumberSet", required = true
                              ) String[] phoneNumberSet,HttpServletRequest req) {
        boolean valid = captchaService.validate(uuid, code);
        if(valid) {
            System.out.println("1111111111111111111111111！"+req.getHeader("sys_org_code"));
            return wechatPaymentService.sendVerifyCode(phoneNumberSet,req.getHeader("sys_org_code"))?

             Result.ok(true):Result.error("发送验证码失败！",false);

        } else {
            return Result.error("图形验证码验证错误");
        }
    }
}
